# Create your views here.
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.conf.urls.defaults import *
from api.models import Author, Book, Price
from django.contrib.humanize.templatetags.humanize import intcomma
from django import template
from django.template import Template


urlpatterns = patterns('product.views',
    (r'^(?P<product_id>\d+)/$',    'detail'),
)

register = template.Library()

@register.filter
def currency(dollars):
    dollars = float(dollars)
    return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])

def host_processor(request):
    return {'request_host': request.get_host()}

def detail(request, product_id):
    books = Book.objects.filter(uuid=product_id)
    authors = None
    prices = None

    if books.count() < 1:
        b = None
    else:
        b = books[0]

        authors = b.author_set.all()
        prices = b.price_set.all()


    t = loader.get_template('product_template.html')
    c = RequestContext(request, {
        'book': b,
        'authors': authors,
        'prices': prices,
    })

    return HttpResponse(t.render(c))

template.builtins.append(register)